package com.atguigu.JUCAuxiliaryClass;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * ClassName: CyclicBarrierDemo
 * Package: com.atguigu.JUCAuxiliaryClass
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/29 20:40
 * version: 1.0
 */
public class CyclicBarrierDemo {
    //案例：组队打BOSS
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
            System.out.println(Thread.currentThread().getName()+"(裁判),所有玩家通过该关卡，请继续...");
        });

        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName()+"模拟第一关");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"第一关通过");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread().getName()+"模拟第二关");
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName()+"第二关通过");
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread().getName()+"模拟第三关");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName()+"第三关通过");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            },"玩家"+i).start();
        }
    }
}
